<?php

declare(strict_types=1);
/*
 * 频率控制
 */

namespace App\Service;

use App\Common\RedisCache;
use App\Constants\Status;
use App\Exception\ApiException;
use App\Job\OutLimitLogAddJob;
use Hyperf\Context\Context;

class RateControl
{
    public function submitLimit($type, $extStr)
    {
        if (redis()->exists($type .'_'.$extStr. '_LIMIT_TIMES')) {
            redis()->incr($type .'_'.$extStr. '_LIMIT_TIMES');
            $limit_err = redis()->get($type .'_'.$extStr. '_LIMIT_TIMES');
            if ($limit_err >= 10) {
                throw new ApiException(-403, '信息提交过于频繁，请稍后再试');
            }
        } else {
            redis()->incr($type .'_'.$extStr. '_LIMIT_TIMES');
            redis()->expire($type .'_'.$extStr. '_LIMIT_TIMES', 60);
        }
        unset($field, $remoteIp, $userData, $platSetting, $time, $counts, $apiController, $apiFunction, $secret, $uid, $rateLimit, $outFee,  $email, $tbName);
    }
    public function errorCheck($key)
    {
        // 超限次数统计（频繁超限处理方式）
        if (redis()->exists('errorLimit:'.$key . ':times')) {
            $limit_err = redis()->get('errorLimit:'.$key . ':times');
            if ($limit_err >= 150) {
                throw new ApiException(-403,'异常访问管控中');
            }
        }
    }
    public function errorLimit($key)
    {
        // 超限次数统计（频繁超限处理方式）
        if (redis()->exists('errorLimit:'.$key . ':times')) {
            redis()->incr('errorLimit:'.$key . ':times');
            $limit_err = redis()->get('errorLimit:'.$key . ':times');
            if ($limit_err >= 150) {
                redis()->expire('errorLimit:'.$key . ':times', 1800);
                throw new ApiException(-403,'异常访问管控');
            }
        } else {
            redis()->incr('errorLimit:'.$key . ':times');
            redis()->expire('errorLimit:'.$key . ':times', 1800);
        }
    }
    public function apiLimit($key,$uid)
    {
    }
}
